package com.situ.stmall.admin.interceptor;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.stmall.admin.entity.APIResult;
import com.situ.stmall.admin.entity.Root;
import com.situ.stmall.admin.service.RootService;
import com.situ.stmall.admin.util.TokenUtil;
import com.situ.stmall.admin.util.TokenUtil.Token;

/**
 * 	Interceptor拦截器		Filter过滤器
 * @author bobzyh
 *
 */
@Component	// 组件
public class RootInterceptor implements HandlerInterceptor{
	
	@Autowired
	private RootService rootService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("拦截器" + request.getRequestURL().toString());
		
		// 如果用户没有登录, 拦截
		// 1. 获取客户端传递来的token字符串
		String strToken = request.getHeader("token");
		if (strToken == null || strToken.length() ==0) {
			// 用户没有登录
			setResponse(response, "用户未登录, 请登录后再进行操作!!");
			// 拦截
			return false;
		}
		
		// 2.解密token, 时间有没有过期
		Token token = TokenUtil.parseToken(strToken);
		
		if (token.getStatus() == 1) {
			setResponse(response, "登录已过期, 请重新登录!!!");
			return false;
		}
		
		// 3. 是不是一个有效的用户  
		String rootname = token.getCode();
		Root root = rootService.getByRootName(rootname);
		if (root == null) {
			setResponse(response, "当前用户不是一个有效用户, 请重新登录!!!");
			return false;
		}
		
		// 4. 禁用
		if (root.getStatus() == 1) {
			setResponse(response, "用户已被禁用, 请联系管理员!!!");
			return false;
		}
		
		// 5. 刷新Token, 重置有效时间
		strToken = TokenUtil.createToken(token.getCode());
		response.setHeader("token", strToken);
		
		return true;	// 放行
	}
	
	/**
	 * 设置用户验证失败时的数据返回
	 * @param response
	 * @param msg
	 * @throws IOException
	 */
	private void setResponse(HttpServletResponse response, String msg) throws IOException {
		APIResult apiResult = APIResult.unauthorized(msg);
		
		// 将apiResult 转换成JSON字符串
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(apiResult);
		
		// 由Response返回
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().write(json);
	}
}
